const Settings = require('../models/settings.model');
const crypto = require('crypto');
const emailService = require('./email.service');

class SettingsService {
  // 获取用户设置
  async getUserSettings(userId) {
    return Settings.getOrCreate(userId);
  }

  // 更新设置
  async updateSettings(userId, section, data) {
    const settings = await Settings.findOne({ userId });
    if (!settings) {
      throw new Error('设置不存在');
    }

    settings[section] = { ...settings[section], ...data };
    return settings.save();
  }

  // 记录设备登录
  async recordDeviceLogin(userId, req) {
    const deviceId = this.generateDeviceId(req);
    const deviceInfo = {
      deviceId,
      deviceName: this.getDeviceName(req),
      deviceType: this.getDeviceType(req),
      ip: req.ip,
      userAgent: req.headers['user-agent']
    };

    const settings = await Settings.getOrCreate(userId);
    return settings.addLoginDevice(deviceInfo);
  }

  // 获取登录设备列表
  async getLoginDevices(userId) {
    const settings = await Settings.findOne({ userId });
    if (!settings) {
      return [];
    }
    return settings.loginDevices.filter(device => device.isActive);
  }

  // 登出设备
  async logoutDevice(userId, deviceId) {
    const settings = await Settings.findOne({ userId });
    if (!settings) {
      throw new Error('设置不存在');
    }
    return settings.removeLoginDevice(deviceId);
  }

  // 测试邮件通知
  async testEmailNotification(userId) {
    const settings = await Settings.findOne({ userId });
    if (!settings?.notifications?.channels?.email) {
      throw new Error('邮件通知未启用');
    }
    return emailService.sendTestEmail(settings.email);
  }

  // 生成设备ID
  generateDeviceId(req) {
    const data = `${req.headers['user-agent']}${req.ip}`;
    return crypto.createHash('md5').update(data).digest('hex');
  }

  // 获取设备名称
  getDeviceName(req) {
    const ua = req.headers['user-agent'];
    if (ua.includes('Windows')) return 'Windows PC';
    if (ua.includes('Macintosh')) return 'Mac';
    if (ua.includes('iPhone')) return 'iPhone';
    if (ua.includes('iPad')) return 'iPad';
    if (ua.includes('Android')) return 'Android';
    return 'Unknown Device';
  }

  // 获取设备类型
  getDeviceType(req) {
    const ua = req.headers['user-agent'];
    if (ua.includes('Mobile')) return 'mobile';
    if (ua.includes('Tablet')) return 'tablet';
    return 'desktop';
  }
}

module.exports = new SettingsService(); 